// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {id} = event;
  console.log(event,'event')
  const result = await cloud.database().collection('mock_car').where({
    productId: id
  }).get()
  if(!result.data.length) {
    const {data: item} = await cloud.database().collection('mock_product').doc(id).field({_id: true, image: true, title:true,price:true}).get()
    console.log(item,'====')
    cloud.database().collection('mock_car').add({
      data: {
        title: item.title,
        price: item.price,
        image: item.image,
        productId: item._id,
        count: 1
      }
    })
  }
  console.log(result)
  return {
    event,
    result: 2,
    data,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}